import { createRouter, createWebHashHistory } from 'vue-router'
// import HomeView from '../views/HomeView.vue'
import store from '@/store/index.js'
const routes = [
  {
    path: '/',
    name: 'login',
    // component: HomeView
    component:()=>import('../views/user/LoginView.vue')
  },
  {
    path:"/admin",
    name:"admin",
    component:()=>import('../views/admin/AdminView.vue'),
    children:[
    //   {name:"dash",path:"dash",component:()=>import('../views/admin/DashView.vue')},
    //   {name:"staff",path:"auth/staffManage",component:()=>import('../views/admin/permission/StaffManage.vue')},
    //   // 角色管理；菜单管理；默认重定向奥员工管理
    //   {name:"usergroup",path:"auth/usergroup",component:()=>import('../views/admin/permission/UserGroup.vue')},
    //   {name:"menu",path:"auth/menu",component:()=>import('../views/admin/permission/MenuManage.vue')},
      // {path:'',redirect:'/admin/dash'}
    ]
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
 
router.beforeEach( async (to,from,next)=>{
  // 要去的页面路由包含admin，我们就处理
  // 如果仓库中菜单的长度为0
  if(to.path.includes("/admin")&&store.state.permission.menus.length===0){
    // 重新执行dispath
    // 执行getMenu这个action是需要时间的
    await store.dispatch("getMenu"); //等待 dispatch 执行完毕（reslove）再执行 next
    // 执行到下面这句的时候getMenu还没有执行完毕，就执行了next（导致递归重复执行）
    // 解决办法是：等待getMenu执行完毕后再执行next：2种方案1回调函数，2是promise
    next({path:to.fullPath})
     
  }else{
    // 否则直接放行
    next();
  }
})
 

export default router
